<template>
	<view class="page">
		<ppc-section :title="isWeight?'历史体重信息':'历史饮食记录'" value="左滑删除"></ppc-section>
		<scroll-view @scrolltolower="lowerBottom" style="height:78vh;" scroll-y="true">
			<uni-swipe-action :style="'width:100%'">
				<uni-swipe-action-item v-for="(item, index) in swipeList" :right-options="item.options" :key="item._id"
					@click="swipeClick(item._id)">
					<view class="box" @click.stop="gotoFoodDetail(item)">
						<view class="itemBox">
							<view class="left">
								{{item.date}}
							</view>
							<view class="right">
								<text class="value">{{item.weight||item.totalCaloric}}</text>
								<text class="unit">{{item.unit||'大卡'}}</text>
							</view>
						</view>
					</view>
				</uni-swipe-action-item>
			</uni-swipe-action>
			<!-- bottomText底部文字 -->
			<view class="medicine_title" v-if="!loading">
				{{isBottom?'没有更多数据了～':'下拉加载更多'}}
			</view>
		</scroll-view>

		<view class="btn" @click="recordClick" v-if="isWeight">
			<text class="text">记录</text>
		</view>
		<uni-popup ref="popup" background-color="#fff" @change="changePopup">
			<view class="popup-content" :class="{ 'popup-height': type === 'left' || type === 'right' }">
				<view class="top">
					<view class="dateCard">
						<!-- 日期弹窗 -->
						<view class="date">
							<uni-datetime-picker type="date" @change="dateChange">{{date}}</uni-datetime-picker>
						</view>
					</view>
				</view>
				<view class="center">
					<picker-view :value="weight" @change="bindChange" class="picker-view">
						<picker-view-column>
							<view class="item" v-for="(item,index) in number" :key="index">{{item}}</view>
						</picker-view-column>
						<picker-view-column>
							<view class="item" v-for="(item,index) in float" :key="index">{{item}}</view>
						</picker-view-column>
						<picker-view-column>
							<view class="item" v-for="(item,index) in unit" :key="index">{{item}}</view>
						</picker-view-column>
					</picker-view>
				</view>

				<!-- 底部按钮 -->
				<view class="bottomBtn">
					<view class="cancel" @click="cancelClick">
						<text>取消</text>
					</view>
					<view class="save" @click="saveClick">
						<text>确定</text>
					</view>
				</view>
			</view>
		</uni-popup>
		<ppc-loading v-if="loading" :isSmall="true"></ppc-loading>
	</view>
</template>

<script setup>
	import {
		ref,
		getCurrentInstance
	} from 'vue';
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import ppcLoading from '/components/ppcLoading.vue'
	import ppcSection from '/components/ppcSection.vue'
	const {
		proxy
	} = getCurrentInstance()
	const data = ref()
	const date = ref()
	const weight = ref([50, .0, '公斤'])
	const popup = ref()
	const isWeight = ref(false)
	const unit = ref(['公斤'])
	const float = ref([])
	const number = ref([])
	const weigthValue = ref()
	const swipeList = ref([])
	const loading = ref(false)
	//判断是否修改数据
	const isUpdate = ref(false)
	//当前页数
	const currentPage = ref(1)
	//每页显示的条数
	const pageSize = ref(10)
	//判断是否触底
	const isBottom = ref(false)
	onLoad((option) => {
		if (option.weight) {
			isWeight.value = true
			date.value = getNowFormatDate()
			getWeight()
			for (let i = 30; i <= 200; i++) {
				number.value.push(i)
			}
			for (let i = 0; i <= 9; i++) {
				float.value.push('.' + i)
			}
		} else if (option.foodRecord) {
			isWeight.value = false
			getFoodRecord()
		}
	})
	const recordClick = () => {
		popup.value.open("bottom")
	}
	//日期选择
	const dateChange = (e) => {
		if (typeof(e) == 'string') {
			date.value = e.replace(/-/g, "/")
		}
	}
	//获取体重信息
	const getWeight = () => {
		loading.value = true
		proxy.$http('getWeight', {
			currentPage: currentPage.value,
			pageSize: pageSize.value
		}).then(res => {
			if (!res.errCode) {
				res.result.data.data.forEach(item => {
					item.options = [{
						text: "删除",
						style: {
							backgroundColor: 'rgb(255,58,49)'
						}
					}]
				})
				swipeList.value = [...swipeList.value, ...res.result.data.data]
				if (res.result.data.affectedDocs < pageSize.value) {
					isBottom.value = true
				}
				loading.value = false
				uni.hideLoading()
			}
		})
	}
	//获取历史饮食记录数据
	const getFoodRecord = () => {
		proxy.$http('getFoodRecord', {
			currentPage: currentPage.value,
			pageSize: pageSize.value
		}).then(res => {
			if (!res.errCode) {
				res.result.data.data.forEach(item => {
					item.options = [{
						text: "删除",
						style: {
							backgroundColor: 'rgb(255,58,49)'
						}
					}]
				})
				swipeList.value = [...swipeList.value, ...res.result.data.data]
				if (res.result.data.affectedDocs < pageSize.value) {
					isBottom.value = true
				}
				loading.value = false
				uni.hideLoading()
			}
		})
	}
	//查看详细饮食信息
	const gotoFoodDetail = (data) => {
		if (!isWeight.value) {
			uni.navigateTo({
				url: `/pages/detailFoodRecord/detailFoodRecord?data=${JSON.stringify(data)}`
			})
		}
	}
	const saveClick = () => {
		uni.showLoading({
			title: '上传数据中',
			mask: true
		})
		const data = Object.assign(weigthValue.value, {
			date: date.value
		})
		proxy.$http('addWeight', data).then(res => {
			if (res.result.code == 200) {
				// getWeight()
				isUpdate.value = true
				swipeList.value.unshift(data)
				// uni.$emit("weight", {
				// 	type: 'add',
				// 	data: data
				// })
				uni.showToast({
					title: res.result.msg,
					icon: 'none',
					duration: 1000
				});
				popup.value.close()
			}
		})
	}
	const cancelClick = () => {
		popup.value.close()
	}
	const getNowFormatDate = () => {
		//昨日时间
		var day = new Date(new Date().getTime());
		var Year = 0;
		var Month = 0;
		var Day = 0;
		var CurrentDate = "";
		//初始化时间
		//Year       = day.getYear();//有火狐下2008年显示108的bug
		Year = day.getFullYear(); //ie火狐下都可以
		Month = day.getMonth() + 1;
		Day = day.getDate();
		CurrentDate = Year + '/'
		if (Month >= 10) {
			CurrentDate += Month + '/'
		} else {
			CurrentDate += "0" + Month + '/';
		}
		if (Day >= 10) {
			CurrentDate += Day ;
		} else {
			CurrentDate += "0" + Day ;
		}
		return CurrentDate;
	}
	//滑动到底部
	const lowerBottom = () => {
		if (!isBottom.value) {
			currentPage.value += 1
			if (isWeight.value) {
				getWeight()
			} else {
				getFoodRecord()
			}
		}
	}
	const bindChange = (e) => {
		weigthValue.value = {
			weight: Number(number.value[e.detail.value[0]] + float.value[e.detail.value[1]]),
			unit: unit.value[0]
		}
	}
	const swipeClick = (id) => {
		uni.showLoading({
			title: '删除中',
			mask: true
		})
		if (isWeight.value) {
			proxy.$http('deleteWeight', {
				id: id
			}).then(res => {
				if (!res.errCode) {
					// getWeight()
					isUpdate.value = true
					swipeList.value = swipeList.value.filter(item => item._id != id)
					// uni.$emit("weight", {
					// 	type: 'delete',
					// 	id: idÎ
					// })
					uni.showToast({
						title: "删除成功",
						icon: 'none',
						duration: 1000
					})
				}
			})
		} else {
			proxy.$http('deleteFoodRecord', {
				id: id
			}).then(res => {
				if (!res.errCode) {
					// getFoodRecord()
					// uni.$emit("food", {
					// 	type: 'delete',
					// 	id: id
					// })
					isUpdate.value = true
					swipeList.value = swipeList.value.filter(item => item._id != id)
					uni.showToast({
						title: "删除成功",
						icon: 'none',
						duration: 1000
					})
				}
			})
		}
	}
	onUnload(() => {
		//如果修改则重新查询
		if (isUpdate.value) {
			uni.$emit('update', {
				type: isWeight.value ? 'weight' : 'food'
			})
		}
	})
</script>

<style lang="scss">
	.page {
		display: flex;
		flex-direction: column;
		justify-content: center;

		.popup-content {
			height: 550rpx;
			display: flex;
			flex-direction: column;

			.top {
				height: 20%;

				.dateCard {
					margin: 2% 0;
					padding-bottom: 2%;
					display: flex;
					align-items: center;
					justify-content: center;
					border-bottom: 1px solid #f1f1f1;

					.date {
						font-size: 32rpx;
						font-weight: bold;
						color: #000;
					}

					.icon {
						position: fixed;
						top: 20rpx;
						right: 20rpx;

					}
				}

				.content {
					margin: 0 20rpx;
				}
			}

			.center {
				height: 70%;

				.picker-view {
					width: 100%;
					height: 100%;
				}

				.item {
					display: flex;
					align-items: center;
					justify-content: center;
					text-align: center;
					font-weight: bold;
				}
			}

			.bottomBtn {
				display: flex;
				align-items: center;
				justify-content: space-between;
				font-size: 32rpx;
				font-weight: bold;

				.cancel {
					border-top: 2rpx solid #87C38F;
					border-bottom: 2rpx solid #87C38F;
					color: #87C38F;
					padding: 18rpx 0;
					width: 50%;
					text-align: center;
				}

				.save {
					width: 50%;
					text-align: center;
					color: #f1f1f1;
					padding: 20rpx 0;
					background-color: #87C38F;
				}
			}
		}
	}

	.box {
		width: 100%;
		// margin: 0 20rpx;
		background-color: #fff;
		border-radius: 30rpx;
		margin: 5rpx 0;

		.itemBox {
			height: 120rpx;
			margin: 0 20rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-bottom: 2rpx dashed #afafaf;

			.left {
				font-size: 30rpx;
				font-weight: bold;
			}

			.value {
				font-size: 38rpx;
				font-weight: bold;
				color: #87C38F;
				margin: 0 20rpx;
			}

			.unit {
				font-size: 30rpx;
				font-weight: bold;
			}
		}

		.itemBox:last-child {
			border-bottom: none
		}
	}

	.btn {
		position: fixed;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #87C38F;
		bottom: 70rpx;
		height: 80rpx;
		width: 80%;
		left: 50%;
		transform: translate(-50%, 0);
		color: #fff;
		font-size: 30rpx;
		font-weight: bold;
		border-radius: 50rpx;
		text-indent: 10rpx;
		letter-spacing: 10rpx;
	}

	.medicine_title {
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 50rpx 0;
		color: #afafaf;
		font-size: 28rpx;
	}
</style>